package com.level.system.service.impl;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.level.system.base.PageBean;
import com.level.system.dao.EmrBasyMapper;
import com.level.system.dao.QcJobMapper;
import com.level.system.dao.QcResultMapper;
import com.level.system.dao.QcRuleMapper;
import com.level.system.entity.EmrBasy;
import com.level.system.entity.QcJob;
import com.level.system.entity.QcResult;
import com.level.system.entity.QcRule;
import com.level.system.entity.VO.QcContrastRuleVO;
import com.level.system.service.QcRuleService;
import com.level.system.util.PageUtil;

/**
 * <p>
 * 质控规则表 服务实现类
 * </p>
 *
 * @author zhaocw
 * @since 2019-05-08
 */
@Service
@SuppressWarnings("all")
public class QcRuleServiceImpl extends ServiceImpl<QcRuleMapper, QcRule> implements QcRuleService {

	private  final Logger logger = LoggerFactory.getLogger(QcRuleServiceImpl.class);
	@Autowired
	private QcRuleMapper qcRuleMapper;
	@Autowired
	private EmrBasyMapper emrBasyMapper;
	@Autowired
	private QcResultMapper qcResultMapper;
	@Autowired
	private QcJobMapper qcJobMapper;
	
	
	public IPage<QcRule> selectPageVo(PageBean<?> pageBean, String state) {
		Page page = PageUtil.pageDataInterchange(pageBean);
		return qcRuleMapper.selectPageVo(page, state);
	}


	public void insertQCRule(QcRule qcRule,String opt) {
		if(qcRule.getId()==null||"".equals(qcRule.getId())) {
			qcRule.setCreatetime(new Date());
			qcRule.setCreater(opt);
			qcRuleMapper.insertQCRule(qcRule);
		}else {
			qcRule.setModifitime(new Date());
			qcRule.setModifier(opt);
			qcRuleMapper.updateById(qcRule);
		}
		
	}


	public void updateQCRule(QcRule qcRule) {
		Validate.notNull(qcRule.getId());
		qcRule.setModifitime(new Date());
		qcRuleMapper.updateById(qcRule);
	}

	/**
	 * 对比
	 */
	public void contrastRule(QcContrastRuleVO VO) {
		//判断病案首页
		contrastRuleForBASY(VO);
	}
	
	/**
	 * 病案首页质控
	 * @param VO
	 */
	private void contrastRuleForBASY(QcContrastRuleVO VO) {
		/**
		 * 查询可以增加条件 QueryWrapper
		 */
		List<QcRule> list_Qc = qcRuleMapper.selectList(new QueryWrapper<QcRule>().in(true, "EMRTYPE", "2"));
		List<Map<String,Object>> list_Emr = emrBasyMapper.selectMaps(new QueryWrapper<EmrBasy>().eq(true, "PATIENTID", VO.getPATIENTID()));
		for(int i=0;i<list_Qc.size();i++) {
			if("2".equals(list_Qc.get(i).getEmrtype())) {
				//只需要循环一次所以直接取出来
				//containsFor(list_Emr.get(0),list_Qc.get(i).getName().toLowerCase());
				Object flag = list_Emr.get(0).get(list_Qc.get(i).getName().toLowerCase());
				//过敏药物判断
				if("SFGM,GMY".equals(list_Qc.get(i).getName())) {
					flag = containsForGMY(list_Emr.get(0),list_Qc.get(i).getName().toLowerCase());
				}
				/**
				 * flag == null表示质控字段匹配为空值
				 *      <> null表示质控字段匹配不为空值     
				 */
				if(flag == null) {
					//记录不符合结果
					QcResult res = qcResultMapper.selectOne(new QueryWrapper<QcResult>().eq(true, "RULE_ID", list_Qc.get(i).getId()).eq(true, "STATUS", "0").eq(true, "PATIENTID", VO.getPATIENTID()));
					if(res==null) {
						QcResult qcResult = new QcResult();
						qcResult.setRuleId(list_Qc.get(i).getId());
						qcResult.setDESCRIPTION(list_Qc.get(i).getDescription());
						qcResult.setPATIENTID(VO.getPATIENTID());
						qcResult.setEMRTYPE(list_Qc.get(i).getEmrtype());
						qcResult.setOPTID(VO.getCREATEDOCTORID());
						qcResult.setOPTNAME(VO.getCREATEDOCTORNAME());
						qcResultMapper.insert(qcResult);
					}
				}else {
					//表示没有匹配上
					QcResult res = qcResultMapper.selectOne(new QueryWrapper<QcResult>().eq(true, "RULE_ID", list_Qc.get(i).getId()).eq(true, "PATIENTID", VO.getPATIENTID()));
					/**
					 * res <> null表示之前此字段有被质控保存过记录
					 */
					if(res!=null) {
						res.setSTATUS("1");
						qcResultMapper.updateById(res);
					}
				}
			}
		}
	}
	
	private Object containsFor(Map<String,Object> map,String str) {
		Object obj = null;
		if(str.contains(",")) {
			String[] str_ = str.split(",");
			if(str_[1].contains(",")) {
				obj = containsFor(map,str_[1]);
			}else {
				obj = map.get(str_[1]);
			}
			if(obj==map.get(str_[0])) {
				return null;
			}
		}
		return 1;
	}
	/**
	 * 过敏药物判断
	 * @param map
	 * @param str
	 * @return
	 */
	private Object containsForGMY(Map<String,Object> map,String str) {
		Object obj = null;
		if(str.contains(",")) {
			String[] str_ = str.split(",");
			if("2".equals(map.get(str_[0]))&&null==map.get(str_[1])) {
				return null;
			}
		}
		return 1;
	}
	
	/**
	 * 字符串反射方法并且执行
	 * @param fieldName
	 * @param goodsVO
	 * @return
	 */
	private static Object getResult(Object fieldName, Object obj) {
        try {
            Class<?> aClass = obj.getClass();
            Field declaredField = aClass.getDeclaredField(fieldName.toString());
            declaredField.setAccessible(true);
            PropertyDescriptor pd = new PropertyDescriptor(declaredField.getName(), aClass);
            Method readMethod = pd.getReadMethod();

            return readMethod.invoke(obj);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

	/**
	 * 定时任务质控
	 */
	public void constrstRuleTask() {
		constrstRuleTaskForBASY();
	}

	/**
	 * 病案首页定时质控
	 */
	private void constrstRuleTaskForBASY() {
		List<QcRule> list_Qc = null;
		List<QcJob> list_job = qcJobMapper.getRowNumList();
		List<Map<String,Object>> list_Emr = null;
		for(int i=0;i<list_job.size();i++) {
			/**
			 * 判断类型
			 */
			if("2".equals(list_job.get(i).getEMRTYPE())) {
				list_Qc = qcRuleMapper.selectList(new QueryWrapper<QcRule>().eq(true, "EMRTYPE", list_job.get(i).getEMRTYPE()));
				/**
				 * 判断为null表示不需要质控  
				 * 退出
				 */
				if(list_Qc==null) continue;
				for(int j=0;j<list_Qc.size();j++) {
					if(list_Emr==null) {
						list_Emr = emrBasyMapper.selectMaps(new QueryWrapper<EmrBasy>().eq(true, "PATIENTID", list_job.get(i).getPATIENTID()));
					}
					Object flag = list_Emr.get(0).get(list_Qc.get(j).getName().toLowerCase());
					//过敏药物判断
					if("SFGM,GMY".equals(list_Qc.get(j).getName())) {
						flag = containsForGMY(list_Emr.get(0),list_Qc.get(j).getName().toLowerCase());
					}
					/**
					 * flag == null表示质控字段匹配为空值
					 *      <> null表示质控字段匹配不为空值     
					 */
					if(flag == null) {
						//记录不符合结果
						QcResult res = qcResultMapper.selectOne(new QueryWrapper<QcResult>().eq(true, "RULE_ID", list_Qc.get(j).getId()).eq(true, "STATUS", "0").eq(true, "PATIENTID", list_job.get(i).getPATIENTID()));
						if(res==null) {
							QcResult qcResult = new QcResult();
							qcResult.setRuleId(list_Qc.get(j).getId());
							qcResult.setDESCRIPTION(list_Qc.get(j).getDescription());
							qcResult.setPATIENTID(list_job.get(i).getPATIENTID());
							qcResult.setEMRTYPE(list_Qc.get(j).getEmrtype());
							qcResult.setOPTID("dba");
							qcResult.setOPTNAME("dba");
							qcResultMapper.insert(qcResult);
						}
					}else {
						//表示没有匹配上
						QcResult res = qcResultMapper.selectOne(new QueryWrapper<QcResult>().eq(true, "RULE_ID", list_Qc.get(j).getId()).eq(true, "PATIENTID", list_job.get(i).getPATIENTID()));
						/**
						 * res <> null表示之前此字段有被质控保存过记录
						 */
						if(res!=null) {
							res.setSTATUS("1");
							qcResultMapper.updateById(res);
						}
					}
				}
			}
			QcJob job = list_job.get(i);
			job.setSTATUS("1");
			qcJobMapper.updateById(job);
		}
	}
}
